package top.suven.base.core.mq.rocketmq;


import top.suven.base.core.redis.RedisClusterServer;
import top.suven.base.core.spring.SpringUtil;
import top.suven.base.util.AopTargetUtils;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * @ClassName:
 * @Description:
 * @Author lixiangling
 * @Date 2018/5/22 19:09
 * @Copyright: (c) 2018 gc by https://www.gc.com.cn/
 * @Version : 1.0.0
 * --------------------------------------------------------
 * modifyer    modifyTime                 comment
 *
 * --------------------------------------------------------
 */
@ConditionalOnClass(RocketMQAutoConfig.class)
public class RocketMQListenerFactory implements FactoryBean<RocketMQListener> {
    private Logger logger = LoggerFactory.getLogger(RocketMQProducerFactory.class);

    private Map<String,RocketMQListener> mqListenerMap;

    public RocketMQListenerFactory(){
        mqListenerMap = new HashMap<>();
        RedisClusterServer redisClusterServer = SpringUtil.getBean(RedisClusterServer.class);
        Collection<RocketMQConsumerHandler> rocketMQConsumerHandlers = new LinkedList<>(SpringUtil.getBeansOfType(RocketMQConsumerHandler.class));
        if(rocketMQConsumerHandlers == null || rocketMQConsumerHandlers.isEmpty()){
            return;
        }
        for (RocketMQConsumerHandler rocketMQConsumerHandler : rocketMQConsumerHandlers){
            rocketMQConsumerHandler = (RocketMQConsumerHandler)AopTargetUtils.getTarget(rocketMQConsumerHandler);
            RocketMqConsumer rocketMqConsumer = rocketMQConsumerHandler.getClass().getAnnotation(RocketMqConsumer.class);
            RocketMQListener rocketMQListener = new RocketMQListener();
            rocketMQListener.setMessageProcessor(rocketMQConsumerHandler);
            rocketMQListener.setRedisClusterServer(redisClusterServer);
            mqListenerMap.put(rocketMqConsumer.topic().getTopicName(), rocketMQListener);
        }
    }

    public RocketMQListener getMQListener(String topicName){
        return mqListenerMap.get(topicName);
    }

    @Override
    public RocketMQListener getObject() throws Exception {
        return null;
    }

    @Override
    public Class<?> getObjectType() {
        return DefaultMQProducer.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}
